package com.zkyc.framework.schedulejob.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.zkyc.framework.schedulejob.utils.JschUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.*;


@Slf4j
@Component
public class DingTalkTask {
    @Autowired
    private RestTemplate restTemplate;

    private static final String url = "https://oapi.dingtalk.com/robot/send?access_token=49d3a4d1a446a97e03b5817a604a91b86529e5006dd4233c80d0160ba1ff3621";
    private static final String ip = "10.101.116.5";
    private static final String username = "root";
    private static final String password = "8qsEGdEaJEvD";
    private static final String TLNP = "netstat -tlnp | grep ";
    private static final String GATEWAY = "web-gateway-0.0.1-SNAPSHOT";
    private static final String WEBSITE = "service-website-0.0.1-SNAPSHOT";
    private static final String USER = "service-user-0.0.1-SNAPSHOT";
    private static final String ALGORITHM = "service-algorithm-0.0.1-SNAPSHOT";
    private static final String SCHEDULE = "schedule-job-0.0.1-SNAPSHOT";
    private static final String FILE = "service-file-0.0.1-SNAPSHOT";
    private static final String REMOTEPATH = "/root/station_group/20220831/jar/";
    private static final String[] SERVICE_NAME = {GATEWAY, WEBSITE, USER, ALGORITHM, SCHEDULE, FILE};
    private static boolean FLAG = false;

    /**
     * 每分钟执行一次
     */
    //@Scheduled(cron = "*/60 * * * * ?")
    public void process() {
        if (FLAG) return;
        JschUtils jschUtils = null;
        try {
            jschUtils = new JschUtils(ip, username, password);
            jschUtils.connectSftp();
            for (int i = 8092; i < 8098; i++) {
                restart(jschUtils, TLNP + i, SERVICE_NAME[i - 8092], i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(jschUtils)) jschUtils.disconnect();
        }

    }

    private void restart(JschUtils jschUtils, String cmd, String name, int host) throws InterruptedException {
        String result = jschUtils.execCmd(cmd);
        if (StringUtils.isBlank(result)) {
            System.out.println(
                    jschUtils.execCmd("cd /root/station_group/20220831/jar/ " +
                            "&& kill 9 $(ps -ef|grep " + name + ".jar | grep -v grep | awk '{print$2}')" +
                            " && nohup java -jar -Xms128M -Xmx256M " + name + ".jar  >  " + name + ".txt &"));
            //sendMsg(name + "服务挂掉了,正在重启");
            System.out.println(name + "服务挂掉了，正在重启");
            do {
                Thread.sleep(10000);
                //sendMsg(name + "重启成功");
                System.out.println(name + "重启成功");
                break;
            } while (!StringUtils.isNotBlank(jschUtils.execCmd(cmd)));

        }
    }

    private void sendMsg(String msg) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> content = new HashMap<>();
        map.put("msgtype", "text");
        map.put("text", content);
        content.put("content", "服务运行状态提醒: " + msg);
        restTemplate.postForObject(url, map, String.class);
    }

    private static void sendMsgToDingTalk(String msg) {
        Map<String, Object> content = new HashMap<>();
        JSONObject params = new JSONObject();
        params.put("msgtype", "text");
        params.put("text", content);
        content.put("content", "服务运行状态提醒: " + msg);
        HttpRequest.post(url)
                .body(params.toJSONString())
                .execute().body();
    }

    /**
     * 部署服务
     **/
    public static void main(String[] args) {
        FLAG = true;
        JschUtils jschUtils = null;
        String packageNum = "1"; //0.部署所有服务 1.部署gateway、website和user 2.部署file（默认值为1）
        try {
            //sendMsgToDingTalk("部署脚本启动");
            //System.out.println("部署脚本启动");
            jschUtils = new JschUtils(ip, username, password);
            jschUtils.connectSftp();
            if (exec("mvn package -Dmaven.test.skip=true -P dev")) {
                //sendMsgToDingTalk("打包完成，开始上传jar包");
                for (int i = 0; i < 6; i++) {
                    if (packageNum.equals("1") && (i != 1 && i != 2 && i != 0)) continue;
                    if (packageNum.equals("2") && i != 5) continue;
                    String localPath = System.getProperty("user.dir") + File.separator +
                            StrUtil.sub(SERVICE_NAME[i], 0, -15) +
                            File.separator + "target" + File.separator;
                    System.out.println(localPath);
                    if (!jschUtils.uploadFile(REMOTEPATH, SERVICE_NAME[i] + ".jar", localPath, SERVICE_NAME[i] + ".jar")) {
                        sendMsgToDingTalk(SERVICE_NAME[i] + "上传失败");
                        //System.out.println(SERVICE_NAME[i]+"上传失败");
                    }
                }
                //System.out.println("上传完成,现有服务已停止,开始部署");
                sendMsgToDingTalk("开始部署，服务已停止");
                jschUtils.execCmd("cd /root/station_group/20220831 && ./start.sh");
                //System.out.println("部署完成");
                Thread.sleep(15000);
                sendMsgToDingTalk("部署完成");
                FLAG = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(jschUtils)) jschUtils.disconnect();
        }
    }

    /**
     * 执行命令
     **/
    public static boolean exec(String command) {
        Process process = null;
        String cmd = getOsCmd() + command;
        try {
            process = Runtime.getRuntime().exec(cmd);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(new String(line.getBytes(), "GBK"));
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            assert process != null;
            process.destroy();
        }
    }

    /**
     * 获取当前操作系统
     **/
    public static String getOsCmd() {
        Properties props = System.getProperties(); //获得系统属性集
        String osName = props.getProperty("os.name"); //操作系统名称
        if (osName.toLowerCase().contains("linux")) {
            return "/bin/sh -c";
        } else if (osName.toLowerCase().contains("windows")) {
            return "cmd /c";
        } else {
            throw new RuntimeException("服务器不是linux|windows操作系统");
        }
    }
}
